package com.system.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.company.model.CompanyInfo;
import com.company.service.CompanyService;
import com.system.model.UserInfo;
import com.system.model.UserLoginInfo;
import com.system.service.LoginService;
import com.system.service.UserInfoService;

@Controller
public class LoginController {
	// 页面actionView的地址
	public static final String toLoginView = "/login";
	public static final String login = "/loginCheck";

	// 页面路径
	public static final String loginPage = "/login";

	@Autowired
	LoginService loginService;
	@Autowired
	CompanyService companyService;
	@Autowired
	UserInfoService userInfoService;

	@RequestMapping(value = toLoginView, method = RequestMethod.GET)
	public ModelAndView toLoginView() {
		ModelAndView mv = new ModelAndView(loginPage);
		return mv;
	}

	@ResponseBody
	@RequestMapping(value = login, method = RequestMethod.POST)
	public Map<String, Object> login(
			@RequestParam(value = "userName", required = false) String userName,
			@RequestParam(value = "password", required = false) String password,
			HttpServletRequest req, HttpServletResponse res) {
		HttpSession session = req.getSession();
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			UserLoginInfo user = loginService.getUserLoginInfo(userName);
			if (user == null) {
				result.put("flag", "error");
				result.put("message", "用户名不存在！");
			} else if (!user.getPassword().equals(password)) {
				result.put("flag", "error");
				result.put("message", "用户名密码错误！");
			} else {
				result.put("flag", "success");
				session.setAttribute("loginId", user.getId());
				UserInfo userInfo = userInfoService.getUserInfo(user.getUserId());
				session.setAttribute("userId", userInfo.getId());
				session.setAttribute("userName", userInfo.getUserName());
				session.setAttribute("companyId", userInfo.getCompanyId());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
